#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "InvoiceStatistics.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_uploadManager(new ImageUploadManager(this))
{
    ui->setupUi(this);

    InvoiceStatistics *invoiceStatsWidget = new InvoiceStatistics(this);
    ui->tabWidget->addTab(invoiceStatsWidget, "发票统计");

    // 初始化上传组件
    initializeUploader();


    connect(ui->queryButton, &QPushButton::clicked, this, &MainWindow::onButtonClicked);

    // 创建快捷键，绑定回车键
    QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_Return), this);
    connect(shortcut, &QShortcut::activated, this, &MainWindow::on_queryButton_clicked);

    // 将上传历史模型设置到表格视图
    ui->tableView->setModel(m_uploadManager->getUploadHistoryModel());
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 连接信号与槽
    connect(m_uploadManager, &ImageUploadManager::uploadProgress,
            this, &MainWindow::updateUploadProgress);
    connect(m_uploadManager, &ImageUploadManager::uploadFinished,
            this, &MainWindow::handleUploadFinished);

    connect(ui->queryResultTableView, &QTableView::clicked, this, &MainWindow::clickimage);


}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::isImageFileName(const QString &fileName)
{
    // 创建正则表达式，匹配以 .png 或 .jpg 结尾的字符串
    QRegularExpression regex("\\.(png|jpg)$");

    // 执行匹配
    QRegularExpressionMatch match = regex.match(fileName);

    // 返回是否匹配
    return match.hasMatch();
}

void MainWindow::initializeUploader()
{

    QiniuConfig * m_config = new QiniuConfig();
    m_uploadManager->initialize(m_config->getAccessKey(), m_config->getSecretKey(), m_config->getBucket(), m_config->getRegion());
}



void MainWindow::on_uploadButton_clicked()
{
    // 重置进度条
    ui->progressBar->setValue(0);

    // 开始上传流程
    m_uploadManager->startUpload();
}

void MainWindow::updateUploadProgress(int percent)
{
    ui->progressBar->setValue(percent);
}

void MainWindow::handleUploadFinished(bool success, const QString &message)
{
    if (success) {
        ui->statusbar->showMessage(message, 5000);
    } else {
        QMessageBox::warning(this, "上传失败", message);
    }
}

void MainWindow::on_recognizeButton_clicked()
{
    // 打开文件选择对话框，选择图片
    QString m_currentFilePath = QFileDialog::getOpenFileName(nullptr,
        "选择图片","C:/Users/admin/Pictures/Saved Pictures",
        "图片文件 (*.png *.jpg *.jpeg)");
    if (m_currentFilePath.isEmpty()) {
        return; // 用户取消选择
    }
    QFileInfo fileInfo(m_currentFilePath);
    qDebug()<<fileInfo.fileName();

    //mysql->setfileInfo(fileInfo);
//    qDebug()<<"文件名为:"<<mysql->getfileInfo().fileName();


    //保存文件信息
//    rec->setFileInfo(m_currentFilePath);

//    qDebug()<<"insert语句为:"<<rec->insertSql();

    QString downUrl = ("http://svxxs5ooh.hn-bkt.clouddn.com/"+fileInfo.fileName());
    //rec->seturl(filename);
    //downUrl.append(fileInfo.fileName());
    QStringList arguments;
    arguments <<"script.py"<< "--filename" <<downUrl;

//    mysql->setFileurl(downUrl);

    // 使用命令行参数传递JSON

//    rec->recognize(arguments,mysql);
    //ImageRecognize *rec = new ImageRecognize(arguments);
    ImageRecognize *rec = new ImageRecognize(arguments);
    QThread *recThread = new QThread();
    rec->setfileinfo(fileInfo);
    rec->moveToThread(recThread);
    connect(recThread,&QThread::started,this,&MainWindow::showStarted);
    connect(rec,&ImageRecognize::Finshed,this,&MainWindow::showcontent);
    connect(recThread,&QThread::started,rec,&ImageRecognize::recognize);
    recThread->start();
    recThread->quit();
    //rec->recognize(arguments);
}



void MainWindow::on_queryButton_clicked()
{
    QString content = ui->queryLineEdit->text();
    qDebug()<< content;
    QStringList arguments;
    arguments <<"request.py" << "--content" <<content;


    ImageRecognize *qry = new ImageRecognize(arguments);

    QThread *qryThread = new QThread();

    qry->moveToThread(qryThread);
    connect(qry,&ImageRecognize::FinshedQuery,this,&MainWindow::showQuery);
    connect(qryThread,&QThread::started,qry,&ImageRecognize::statis);
    qryThread->start();
    qryThread->quit();
}


void MainWindow::clickimage()
{
    QItemSelectionModel *selectionModel = ui->queryResultTableView->selectionModel();
    QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
    foreach (const QModelIndex &index, selectedIndexes) {
        int row = index.row();
        int column = index.column();
        QString text = index.data(Qt::DisplayRole).toString();
        if(isImageFileName(text)){
            ImageDownloader *img = new ImageDownloader(text,this);
            img->show();
        }
        qDebug() << "选中单元格: 行=" << row << "列=" << column << "值=" << text;
    }
}

void MainWindow::showcontent(const QString &content)
{
    ui->recognizeResultText->setText(content);
}

void MainWindow::showStarted()
{
    ui->recognizeResultText->setText("正在识别中，请稍后");
}

void MainWindow::showQuery(QStandardItemModel *table)
{
    ui->queryResultTableView->setModel(table);
    ui->queryResultTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}




